<?php

namespace App\Http\Middleware;

use App\Http\Controllers\Users\RegisterController;
use Closure;
use Illuminate\Support\Facades\Auth;

class CheckIfLogin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (!$this->isBackend($request)) {
            // 前台验证
            if (!Auth::check() && !$this->isPathLogin($request)) {
                return redirect('/user/login');
            }
        }
        return $next($request);
    }

    public function isBackend(\Illuminate\Http\Request $request)
    {
        return substr($request->path(), 0, 5) == 'admin';
    }

    public function isPathLogin(\Illuminate\Http\Request $request)
    {
        $controller = $request->route()->controller;
        if ($controller instanceof \App\Http\Controllers\Users\LoginController
            || $controller instanceof \App\Http\Controllers\Users\RegisterController
        ) {
            return true;
        }
        return false;
    }
}
